refactor: centralize embedded subscription fetch and eliminate duplicate room calls#40188
Conversation
|
Looks like this PR is not ready to merge, because of the following issues:
Please fix the issues and try again If you have any trouble, please check the PR guidelines |
|
WalkthroughThe changes refactor embedded room loading to fix a race condition where stores were marked ready before subscription data loaded. A new context-based approach defers store readiness until room data is fully fetched, with on-demand subscription fetching added to the Changes
Estimated code review effort🎯 3 (Moderate) | ⏱️ ~25 minutes Suggested labels
🚥 Pre-merge checks | ✅ 4 | ❌ 1❌ Failed checks (1 warning)
✅ Passed checks (4 passed)
✏️ Tip: You can configure your own custom pre-merge checks in the settings. Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out. Comment |
Codecov Report❌ Patch coverage is Additional details and impacted files@@ Coverage Diff @@
## fix/embedded-mode-subscription-race-condition #40188 +/- ##
=================================================================================
+ Coverage 70.20% 70.55% +0.35%
=================================================================================
Files 3278 3275 -3
Lines 116622 116910 +288
Branches 20766 21173 +407
=================================================================================
+ Hits 81871 82486 +615
- Misses 31467 32367 +900
+ Partials 3284 2057 -1227
Flags with carried forward coverage won't be shown. Click here to find out more. 🚀 New features to boost your workflow:
|
|
@coderabbitai review |
✅ Actions performedReview triggered.
|
There was a problem hiding this comment.
🧹 Nitpick comments (1)
apps/meteor/client/views/room/hooks/useOpenRoom.ts (1)
80-91: Drop inline comments per repo style.The coding guideline for
**/*.{ts,tsx,js}says to avoid code comments in the implementation. The intent (on-demand fetch for embedded mode, swallow errors to fall through) is already clear from the code; the explanatory comments on lines 80–81 and 89 can be removed.♻️ Proposed diff
- // The subscription may not be in the store yet — mainly in embedded mode, which skips - // the full subscription list preload. Fetch it on demand if missing. if (user && !Subscriptions.state.find((record) => record.rid === reference || record.name === reference)) { try { const { subscription } = await getSubscription({ roomId: room._id }); if (subscription) { await SubscriptionsCachedStore.upsertSubscription(mapSubscriptionFromApi(subscription)); } - } catch { - // Fall through to existing not-subscribed handling. - } + } catch { + /* noop */ + } }As per coding guidelines: "Avoid code comments in the implementation".
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@apps/meteor/client/views/room/hooks/useOpenRoom.ts` around lines 80 - 91, Remove the inline explanatory comments that precede and inside the try/catch in useOpenRoom: delete the comment about on-demand fetch for embedded mode above the if that checks Subscriptions.state and the comment inside the catch that notes swallowing errors; leave the existing logic intact (the if block that calls getSubscription, the await SubscriptionsCachedStore.upsertSubscription(mapSubscriptionFromApi(subscription)), and the empty catch block) so behavior is unchanged.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.
Nitpick comments:
In `@apps/meteor/client/views/room/hooks/useOpenRoom.ts`:
- Around line 80-91: Remove the inline explanatory comments that precede and
inside the try/catch in useOpenRoom: delete the comment about on-demand fetch
for embedded mode above the if that checks Subscriptions.state and the comment
inside the catch that notes swallowing errors; leave the existing logic intact
(the if block that calls getSubscription, the await
SubscriptionsCachedStore.upsertSubscription(mapSubscriptionFromApi(subscription)),
and the empty catch block) so behavior is unchanged.
ℹ️ Review info
⚙️ Run configuration
Configuration used: Organization UI
Review profile: CHILL
Plan: Pro
Run ID: 3b0fd510-2dce-4a58-9826-1e6498d87375
📒 Files selected for processing (5)
apps/meteor/client/views/room/RoomOpenerEmbedded.tsxapps/meteor/client/views/room/hooks/useOpenRoom.tsapps/meteor/client/views/room/hooks/useOpenRoomParams.tsapps/meteor/client/views/root/MainLayout/EmbeddedPreload.tsxapps/meteor/client/views/root/MainLayout/EmbeddedRoomPreload.tsx
📜 Review details
⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (13)
- GitHub Check: 🔨 Test UI (EE) / MongoDB 8.0 coverage (5/5)
- GitHub Check: 🔨 Test UI (EE) / MongoDB 8.0 coverage (1/5)
- GitHub Check: 🔨 Test UI (EE) / MongoDB 8.0 coverage (2/5)
- GitHub Check: 🔨 Test UI (EE) / MongoDB 8.0 coverage (3/5)
- GitHub Check: 🔨 Test UI (CE) / MongoDB 8.0 (3/4)
- GitHub Check: 🔨 Test UI (EE) / MongoDB 8.0 coverage (4/5)
- GitHub Check: 🔨 Test UI (CE) / MongoDB 8.0 (1/4)
- GitHub Check: 🔨 Test UI (CE) / MongoDB 8.0 (4/4)
- GitHub Check: 🔨 Test UI (CE) / MongoDB 8.0 (2/4)
- GitHub Check: 🔨 Test API Livechat (EE) / MongoDB 8.0 coverage (1/1)
- GitHub Check: 🔨 Test API (EE) / MongoDB 8.0 coverage (1/1)
- GitHub Check: 🔨 Test API (CE) / MongoDB 8.0 (1/1)
- GitHub Check: 🔨 Test Federation Matrix
🧰 Additional context used
📓 Path-based instructions (1)
**/*.{ts,tsx,js}
📄 CodeRabbit inference engine (.cursor/rules/playwright.mdc)
**/*.{ts,tsx,js}: Write concise, technical TypeScript/JavaScript with accurate typing in Playwright tests
Avoid code comments in the implementation
Files:
apps/meteor/client/views/room/RoomOpenerEmbedded.tsxapps/meteor/client/views/room/hooks/useOpenRoom.tsapps/meteor/client/views/root/MainLayout/EmbeddedRoomPreload.tsxapps/meteor/client/views/room/hooks/useOpenRoomParams.tsapps/meteor/client/views/root/MainLayout/EmbeddedPreload.tsx
🧠 Learnings (15)
📓 Common learnings
Learnt from: ggazzo
Repo: RocketChat/Rocket.Chat PR: 35995
File: apps/meteor/app/api/server/v1/rooms.ts:1107-1112
Timestamp: 2026-02-23T17:53:18.785Z
Learning: In Rocket.Chat PR reviews, maintain strict scope boundaries—when a PR is focused on a specific endpoint (e.g., rooms.favorite), avoid reviewing or suggesting changes to other endpoints that were incidentally refactored (e.g., rooms.invite) unless explicitly requested by maintainers.
Learnt from: ricardogarim
Repo: RocketChat/Rocket.Chat PR: 40100
File: apps/meteor/client/views/root/MainLayout/EmbeddedPreload.tsx:18-35
Timestamp: 2026-04-13T16:40:55.864Z
Learning: In Rocket.Chat's embedded mode (`?layout=embedded`), route changes are driven by the parent frame reloading the iframe URL, which causes a full remount of the React tree (including `EmbeddedPreload` at `apps/meteor/client/views/root/MainLayout/EmbeddedPreload.tsx`). The component never survives a navigation, so `roomParams` (computed via `useMemo`) is always fresh on mount. A `[router]` singleton as the sole `useMemo` dependency is therefore correct and intentional — do not flag it as a stale-dependency bug in this component.
📚 Learning: 2026-04-13T16:40:55.864Z
Learnt from: ricardogarim
Repo: RocketChat/Rocket.Chat PR: 40100
File: apps/meteor/client/views/root/MainLayout/EmbeddedPreload.tsx:18-35
Timestamp: 2026-04-13T16:40:55.864Z
Learning: In Rocket.Chat's embedded mode (`?layout=embedded`), route changes are driven by the parent frame reloading the iframe URL, which causes a full remount of the React tree (including `EmbeddedPreload` at `apps/meteor/client/views/root/MainLayout/EmbeddedPreload.tsx`). The component never survives a navigation, so `roomParams` (computed via `useMemo`) is always fresh on mount. A `[router]` singleton as the sole `useMemo` dependency is therefore correct and intentional — do not flag it as a stale-dependency bug in this component.
Applied to files:
apps/meteor/client/views/room/RoomOpenerEmbedded.tsxapps/meteor/client/views/room/hooks/useOpenRoom.tsapps/meteor/client/views/root/MainLayout/EmbeddedRoomPreload.tsxapps/meteor/client/views/room/hooks/useOpenRoomParams.tsapps/meteor/client/views/root/MainLayout/EmbeddedPreload.tsx
📚 Learning: 2025-10-28T16:53:42.761Z
Learnt from: ricardogarim
Repo: RocketChat/Rocket.Chat PR: 37205
File: ee/packages/federation-matrix/src/FederationMatrix.ts:296-301
Timestamp: 2025-10-28T16:53:42.761Z
Learning: In the Rocket.Chat federation-matrix integration (ee/packages/federation-matrix/), the createRoom method from rocket.chat/federation-sdk will support a 4-argument signature (userId, roomName, visibility, displayName) in newer versions. Code using this 4-argument call is forward-compatible with planned library updates and should not be flagged as an error.
Applied to files:
apps/meteor/client/views/room/RoomOpenerEmbedded.tsxapps/meteor/client/views/room/hooks/useOpenRoom.ts
📚 Learning: 2026-03-27T14:52:56.865Z
Learnt from: dougfabris
Repo: RocketChat/Rocket.Chat PR: 39892
File: apps/meteor/client/views/room/contextualBar/Threads/Thread.tsx:150-155
Timestamp: 2026-03-27T14:52:56.865Z
Learning: In Rocket.Chat, there are two different `ModalBackdrop` components with different prop APIs. During review, confirm the import source: (1) `rocket.chat/fuselage` `ModalBackdrop` uses `ModalBackdropProps` based on `BoxProps` (so it supports `onClick` and other Box/DOM props) and does not have an `onDismiss` prop; (2) `rocket.chat/ui-client` `ModalBackdrop` uses a narrower props interface like `{ children?: ReactNode; onDismiss?: () => void }` and handles Escape keypress and outside mouse-up, and it does not forward arbitrary DOM props such as `onClick`. Flag mismatched props (e.g., `onDismiss` passed to the fuselage component or `onClick` passed to the ui-client component) and ensure the usage matches the correct component being imported.
Applied to files:
apps/meteor/client/views/room/RoomOpenerEmbedded.tsxapps/meteor/client/views/root/MainLayout/EmbeddedRoomPreload.tsxapps/meteor/client/views/root/MainLayout/EmbeddedPreload.tsx
📚 Learning: 2026-03-09T18:39:21.178Z
Learnt from: Harxhit
Repo: RocketChat/Rocket.Chat PR: 39476
File: apps/meteor/server/methods/addAllUserToRoom.ts:0-0
Timestamp: 2026-03-09T18:39:21.178Z
Learning: In apps/meteor/server/methods/addAllUserToRoom.ts, the implementation uses a single cursor pass (Users.find(userFilter).batchSize(100)) that collects both the full user objects (collectedUsers: IUser[]) and their usernames (usernames: string[]) in one iteration. `beforeAddUserToRoom` is then called once with the full usernames batch (preserving batch-validation semantics), and the subsequent subscription/message processing loop iterates over the same stable `collectedUsers` array — no second DB query is made. This avoids any race condition between validation and processing while preserving the original batch-validation behavior.
Applied to files:
apps/meteor/client/views/room/hooks/useOpenRoom.ts
📚 Learning: 2026-03-11T22:04:20.529Z
Learnt from: juliajforesti
Repo: RocketChat/Rocket.Chat PR: 39545
File: apps/meteor/client/views/room/body/hooks/useHasNewMessages.ts:59-61
Timestamp: 2026-03-11T22:04:20.529Z
Learning: In `apps/meteor/client/views/room/body/hooks/useHasNewMessages.ts`, the `msg.u._id === uid` early-return in the `streamNewMessage` handler is intentional: the "New messages" indicator is designed to notify about messages from other users only. Self-sent messages — including those sent from a different session/device — are always skipped, by design. Do not flag this as a multi-session regression.
Applied to files:
apps/meteor/client/views/room/hooks/useOpenRoom.tsapps/meteor/client/views/root/MainLayout/EmbeddedPreload.tsx
📚 Learning: 2025-09-25T09:59:26.461Z
Learnt from: Dnouv
Repo: RocketChat/Rocket.Chat PR: 37057
File: packages/apps-engine/src/definition/accessors/IUserRead.ts:23-27
Timestamp: 2025-09-25T09:59:26.461Z
Learning: AppUserBridge.getUserRoomIds in apps/meteor/app/apps/server/bridges/users.ts always returns an array of strings by mapping subscription documents to room IDs, never undefined, even when user has no room subscriptions.
Applied to files:
apps/meteor/client/views/room/hooks/useOpenRoom.ts
📚 Learning: 2025-09-25T09:59:26.461Z
Learnt from: Dnouv
Repo: RocketChat/Rocket.Chat PR: 37057
File: packages/apps-engine/src/definition/accessors/IUserRead.ts:23-27
Timestamp: 2025-09-25T09:59:26.461Z
Learning: AppUserBridge.getUserRoomIds in apps/meteor/app/apps/server/bridges/users.ts always returns an array of strings (mapping subscription documents to room IDs), never undefined, even when user has no room subscriptions.
Applied to files:
apps/meteor/client/views/room/hooks/useOpenRoom.ts
📚 Learning: 2026-02-25T20:10:16.987Z
Learnt from: ahmed-n-abdeltwab
Repo: RocketChat/Rocket.Chat PR: 38913
File: packages/ddp-client/src/legacy/types/SDKLegacy.ts:34-34
Timestamp: 2026-02-25T20:10:16.987Z
Learning: In the RocketChat/Rocket.Chat monorepo, packages/ddp-client and apps/meteor do not use TypeScript project references. Module augmentations in apps/meteor (e.g., declare module 'rocket.chat/rest-typings') are not visible when compiling packages/ddp-client in isolation, which is why legacy SDK methods that depend on OperationResult types for OpenAPI-migrated endpoints must remain commented out.
Applied to files:
apps/meteor/client/views/room/hooks/useOpenRoom.tsapps/meteor/client/views/root/MainLayout/EmbeddedPreload.tsx
📚 Learning: 2025-11-27T17:56:26.050Z
Learnt from: MartinSchoeler
Repo: RocketChat/Rocket.Chat PR: 37557
File: apps/meteor/client/views/admin/ABAC/AdminABACRooms.tsx:115-116
Timestamp: 2025-11-27T17:56:26.050Z
Learning: In Rocket.Chat, the GET /v1/abac/rooms endpoint (implemented in ee/packages/abac/src/index.ts) only returns rooms where abacAttributes exists and is not an empty array (query: { abacAttributes: { $exists: true, $ne: [] } }). Therefore, in components consuming this endpoint (like AdminABACRooms.tsx), room.abacAttributes is guaranteed to be defined for all returned rooms, and optional chaining before calling array methods like .join() is sufficient without additional null coalescing.
Applied to files:
apps/meteor/client/views/room/hooks/useOpenRoom.ts
📚 Learning: 2025-12-09T20:01:07.355Z
Learnt from: sampaiodiego
Repo: RocketChat/Rocket.Chat PR: 37532
File: ee/packages/federation-matrix/src/FederationMatrix.ts:920-927
Timestamp: 2025-12-09T20:01:07.355Z
Learning: In Rocket.Chat's federation invite handling (ee/packages/federation-matrix/src/FederationMatrix.ts), when a user rejects an invite via federationSDK.rejectInvite(), the subscription cleanup happens automatically through an event-driven flow: Matrix emits a leave event back, which is processed by handleLeave() in ee/packages/federation-matrix/src/events/member.ts, and that function calls Room.performUserRemoval() to clean up the subscription. No explicit cleanup is needed in the reject branch of handleInvite() because the leave event handler takes care of it.
<!-- </add_learning>
Applied to files:
apps/meteor/client/views/room/hooks/useOpenRoom.ts
📚 Learning: 2026-02-10T16:32:42.586Z
Learnt from: tassoevan
Repo: RocketChat/Rocket.Chat PR: 38528
File: apps/meteor/client/startup/roles.ts:14-14
Timestamp: 2026-02-10T16:32:42.586Z
Learning: In Rocket.Chat's Meteor client code, DDP streams use EJSON and Date fields arrive as Date objects; do not manually construct new Date() in stream handlers (for example, in sdk.stream()). Only REST API responses return plain JSON where dates are strings, so implement explicit conversion there if needed. Apply this guidance to all TypeScript files under apps/meteor/client to ensure consistent date handling in DDP streams and REST responses.
Applied to files:
apps/meteor/client/views/room/hooks/useOpenRoom.tsapps/meteor/client/views/room/hooks/useOpenRoomParams.ts
📚 Learning: 2026-02-26T19:25:44.063Z
Learnt from: gabriellsh
Repo: RocketChat/Rocket.Chat PR: 38778
File: packages/ui-voip/src/providers/useMediaSession.ts:192-192
Timestamp: 2026-02-26T19:25:44.063Z
Learning: In the Rocket.Chat repository, do not reference Biome lint rules in code review feedback. Biome is not used even if biome.json exists; only reference Biome rules if there is explicit, project-wide usage documented. For TypeScript files, review lint implications without Biome guidance unless the project enables Biome rules.
Applied to files:
apps/meteor/client/views/room/hooks/useOpenRoom.tsapps/meteor/client/views/room/hooks/useOpenRoomParams.ts
📚 Learning: 2026-02-26T19:25:44.063Z
Learnt from: gabriellsh
Repo: RocketChat/Rocket.Chat PR: 38778
File: packages/ui-voip/src/providers/useMediaSession.ts:192-192
Timestamp: 2026-02-26T19:25:44.063Z
Learning: In this repository (RocketChat/Rocket.Chat), Biome lint rules are not used even if a biome.json exists. When reviewing TypeScript files (e.g., packages/ui-voip/src/providers/useMediaSession.ts), ensure lint suggestions do not reference Biome-specific rules. Rely on general ESLint/TypeScript lint rules and project conventions instead.
Applied to files:
apps/meteor/client/views/room/hooks/useOpenRoom.tsapps/meteor/client/views/room/hooks/useOpenRoomParams.ts
📚 Learning: 2026-03-15T14:31:28.969Z
Learnt from: amitb0ra
Repo: RocketChat/Rocket.Chat PR: 39647
File: apps/meteor/app/api/server/v1/users.ts:710-757
Timestamp: 2026-03-15T14:31:28.969Z
Learning: In RocketChat/Rocket.Chat, the `UserCreateParamsPOST` type in `apps/meteor/app/api/server/v1/users.ts` (migrated from `packages/rest-typings/src/v1/users/UserCreateParamsPOST.ts`) intentionally has `fields: string` (non-optional) and `settings?: IUserSettings` without a corresponding AJV schema entry. This is a pre-existing divergence carried over verbatim from the original rest-typings source (PR `#39647`). Do not flag this type/schema misalignment during the OpenAPI migration review — it is tracked as a separate follow-up fix.
Applied to files:
apps/meteor/client/views/room/hooks/useOpenRoomParams.ts
🔇 Additional comments (4)
apps/meteor/client/views/room/RoomOpenerEmbedded.tsx (1)
31-49: LGTM — context consumption is clean and removes the duplicateuseOpenRoomcall.Subscribing to
${uid}/subscriptions-changedkeyed on the resolvedridis correct, and the effect early-returns until bothuidandridare known.apps/meteor/client/views/root/MainLayout/EmbeddedRoomPreload.tsx (1)
10-32: LGTM — readiness now gated on actual room resolution.Deferring
SubscriptionsCachedStore.setReady/RoomsCachedStore.setReadyuntiluseOpenRoomfinishes loading directly addresses the CORE-1555 race where stores were marked ready before subscription data existed. RenderingPageLoadinguntiluseMainReady()and the query both settle keeps the flow deterministic.apps/meteor/client/views/room/hooks/useOpenRoomParams.ts (1)
9-35: LGTM — tidy router → params extraction with proper subscription cleanup.Returning
router.subscribeToRouteChange(...)fromuseLayoutEffectcorrectly wires unsubscribe on unmount/routerchange, and initializing state lazily via() => extractFromRouter(router)avoids a redundant first render.apps/meteor/client/views/root/MainLayout/EmbeddedPreload.tsx (1)
22-42: No action needed. Route registration at line 176 ofroomCoordinator.tsxrequires all three conditions:roomConfig.route?.path,roomConfig.route.name, anddirectives.extractOpenRoomParams. Since routes are only registered whenextractOpenRoomParamsexists, anduseOpenRoomParams()checks for it before returning params, the two code paths are safely aligned.RoomOpenerEmbeddedwill only render within embedded layout whenEmbeddedRoomContext.Provideris present.> Likely an incorrect or invalid review comment.
Proposed changes
EmbeddedPreloadanduseOpenRoomboth calledgetRoomByTypeAndName- the room was fetched twice per navigation in embedded mode.Solution:
EmbeddedPreloadnow drivesuseOpenRoomdirectly and passes the resolved state via context toRoomOpenerEmbedded. The subscription fetch (needed because embedded mode skips the full.listen()preload) was moved intouseOpenRoomitself, so there's a single source of truth for the entire open-room flow.What changed:
useOpenRoom- fetches the room's subscription on demand when it's not in the storeuseOpenRoomParams(new) - reusable hook that extracts{type, reference}from the current routeEmbeddedPreload- orchestratesuseOpenRoom, exposes result via contextEmbeddedRoomPreload(new) - handles the room preload lifecycle (split fromEmbeddedPreloadto satisfyreact/no-multi-comp)RoomOpenerEmbedded- consumes the context instead of callinguseOpenRoomagainNormal (non-embedded) flow is unchanged - the subscription fetch only runs when the sub isn't already in state.
Issue(s)
Follow-up to #40100 (CORE-1555)
Steps to test or reproduce
/channel/general?layout=embeddedwith a non-admin user (withoutpreview-c-room). Room should load normally.Summary by CodeRabbit
Bug Fixes
Refactor